package gold.enterprise;

import java.util.Arrays;

public class TencentPCGThree {


    public static int smallestDifference(int[] ar1, int[] ar2) {
        long[] arr1 = new long[ar1.length];
        long[] arr2 = new long[ar2.length];
        for (int i = 0; i < ar1.length; i++) {
            arr1[i] = ar1[i];
        }

        for (int i = 0; i < ar2.length; i++) {
            arr2[i] = ar2[i];
        }

        Arrays.sort(arr1);
        Arrays.sort(arr2);  //数组先升序排列

        long minDiff = Long.MAX_VALUE;
        int i = 0, j = 0;
        while (i < arr1.length && j < arr2.length) {
            minDiff = Math.min(minDiff, Math.abs(arr1[i] - arr2[j]));

            if (arr1[i] < arr2[j]) {
                i++;
            } else {
                j++;
            }
        }
        return ((int) minDiff);
    }

    public static int findMinByBinarySearch(int value, int[] arr) {
        int left = 0, right = arr.length - 1, mid, minDiff = Integer.MAX_VALUE;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (Math.abs(arr[mid] - value) < minDiff) {
                minDiff = Math.abs(arr[mid] - value);
                if (mid < arr.length - 1 && Math.abs(arr[mid + 1] - value) < Math.abs(arr[mid] - value)) {
                    left = mid + 1;
                    continue;
                } else {
                    right = mid - 1;
                }
            }
            ++left;
        }

        return minDiff;
    }


    public static void main(String[] args) {
        //Scanner in = new Scanner(System.in);
        //int a = in.nextInt();
        //System.out.println(a);
        int[] arr1 = {1, 3, 15, 11, 2};
        int[] arr2 = {23, 127, 235, 19, 8};
        System.out.println(smallestDifference(arr1, arr2));
    }

}


